import { createRouter, createWebHashHistory } from 'vue-router'

// 导入组件
import Login from '../views/LoginView'
import Register from '../components/individual/RegisterView'
import Home from '../views/HomeView'
import Public from '../views/PublicView'
import Shop from '../views/ShopView'
import My from '../views/MyView'
import ShopDetail from '../components/good/ShopGood'
import PubilcEvent from '../components/good/PublicEvent'
import MyPublic from '../components/good/MyPublic'

import Recover from '../components/recover/RecoverView'

import MyAddress from '../components/address/MyaddressView'
import AddressAdd from '../components/address/AddressAdd'
import AddressDetail from '../components/address/AddressDetail'

import ShopOrder from '../components/order/ShopOrder'
import WasteOrder from '../components/order/WasteOrder'

import Point from '../components/individual/PointView'
import Setting from '../components/setting/SettingView'

import Introduce from '../components/aboutus/IntroduceView'
import Message from '../components/individual/ShowMsg'

import PhoneCode from '../components/individual/PhoneCode'
import ResetPwd from '../components/individual/ResetPassword'

const routes = [
  { path: '/', redirect: '/home' },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/home', component: Home },
  { path: '/public', component: Public },
  { path: '/pubevent', name: 'pubevent', component: PubilcEvent },
  { path: '/my', component: My },
  { path: '/shop', component: Shop },
  { path: '/shop/:id', component: ShopDetail, props: true },

  {
    path: '/recover',
    name: 'recover',
    component: Recover,
    meta: {
      keepAlive: true
    }
  },

  { path: '/address', component: MyAddress }, // 地址
  { path: '/address/add', component: AddressAdd },
  { path: '/address/:id', component: AddressDetail, props: true },

  { path: '/shoporder', name: 'shopOrder', component: ShopOrder },
  { path: '/wasteorder', name: 'wasteOrder', component: WasteOrder },

  { path: '/point', component: Point },
  { path: '/setting', component: Setting },
  { path: '/introduce', component: Introduce },
  { path: '/message', component: Message },
  { path: '/mypub', component: MyPublic },
  { path: '/phonecode', component: PhoneCode },
  { path: '/resetpwd', name: 'resetpwd', component: ResetPwd }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  document.body.scrollTop = 0
  document.documentElement.scrollTop = 0
  window.pageYOffset = 0
  if (
    to.path !== '/login' &&
    to.path !== '/register' &&
    to.path !== '/phonecode' &&
    to.path !== '/resetpwd'
  ) {
    const token = window.sessionStorage.getItem('token')
    if (!token) {
      // token没有值
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
